from django.shortcuts import render, HttpResponseRedirect, reverse, redirect
from .models import *
from hashlib import md5


# Create your views here.
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        pwd = md5(pwd.encode('utf-8')).hexdigest()
        ischeck = request.POST.get('ischeck')
        user = User.objects.filter(username=username, pwd=pwd).first()
        if user:
            if ischeck:
                request.session['user'] = {'username': user.username, 'nickname': user.nickname,
                                           'id': user.id, 'identity': user.identity}
            return redirect(reverse('home'))
        else:
            return render(request, 'login.html', {'error': '账号或密码错误！'})

    else:
        return render(request, 'login.html')


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        pwd = md5(pwd.encode('utf-8')).hexdigest()
        nickname = request.POST.get('nickname')
        User.objects.create(username=username, pwd=pwd, nickname=nickname)
        return HttpResponseRedirect(reverse('login'))

    else:
        return render(request, 'register.html')


def loginout(request):
    request.session.clear()
    return redirect(reverse('home'))
